<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/12/19
// +----------------------------------------------------------------------

namespace app\command;

use app\common\facade\Arr;
use app\common\services\JobOptionService;
use Carbon\Carbon;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 该脚本一天运行一次，定在每天 01:00:00 分开始执行
 * Class JobOptionAutoCommand
 * @package ${NAMESPACE}
 * @author feraner<feraner@163.com>
 * @date 2019/12/19
 */
class JobOptionAutoCommand extends BasicCommand
{

    protected $name = 'jobs:apply-finished';

    protected $desc = '自动关闭兼职申请,自动完成兼职';


    /**
     * @param Input  $input
     * @param Output $output
     *
     * @return int|null|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function execute(Input $input, Output $output)
    {

        //程序运行顺序不能改变,有先后顺序

        //1:自动完成兼职
        $this->__autoFinishJob();


        //2:关闭申请兼职通道
        $this->__autoCloseApplyJob();



    }


    /**
     * 自动完成兼职 【处理兼职工作7天后还没有点击自动完成的兼职】
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __autoFinishJob()
    {
        $timeRange = $this->__getFinishJobTimeRange();
        $limit = [
            'offset'        => 0,
            'length'        => 20
        ];
        while (true) {
            $jobList = $this->__getJobList($timeRange, $limit, 4);
            if ($jobList) {
                foreach ($jobList as $jobItem) {
                    $tmpJobInfo = Db::name('jobs')
                        ->where('id', Arr::get($jobItem, 'id'))
                        ->find() ?: [];
                    if ($tmpJobInfo) {
                        try {
                            $result = (new JobOptionService())->doneJob($tmpJobInfo);
                        } catch (\Exception $e) {

                        }
                    }
                }

                $limit['offset'] += $limit['length'];
            } else {
                break;
            }
            sleep(2);
        }
    }








    /**
     * 自动关闭兼职申请通道 [处理昨天是工作时间却没有关闭兼职工作申请的兼职]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __autoCloseApplyJob()
    {
        $timeRange = $this->__getCloseApplyTimeRange();
        $limit = [
            'offset'        => 0,
            'length'        => 20
        ];
        while (true) {
            $jobList = $this->__getJobList($timeRange, $limit, 2);
            if ($jobList) {
                foreach ($jobList as $jobItem) {
                    $tmpJobInfo = Db::name('jobs')
                        ->where('id', Arr::get($jobItem, 'id'))
                        ->find() ?: [];
                    if ($tmpJobInfo) {
                        try {
                            $result = (new JobOptionService())->closeApplyJob(
                                $tmpJobInfo,
                                Arr::get($tmpJobInfo, 'user_id'),
                                Arr::get($tmpJobInfo, 'admin_id', 0)
                            );
                        } catch (\Exception $e) {

                        }
                    }
                }
                $limit['offset'] += $limit['length'];
            } else {
                break;
            }
            sleep(2);
        }
    }




    /**
     * 获取需要操作的兼职列表
     * @param $timeRange
     * @param $limit
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function __getJobList($timeRange, $limit, $status)
    {
        $jobList = Db::name('jobs')
            ->where('status', $status)
            ->where('is_deleted', 0)
            ->where('work_time', '>=', Arr::get($timeRange, 'dayTimeStart'))
            ->where('work_time', '<=', Arr::get($timeRange, 'dayTimeEnd'))
            ->limit(Arr::get($limit, 'offset'), Arr::get($limit, 'length'))
            ->field('id,user_id,work_time,status,is_deleted')
            ->select() ?: [];

        return $jobList;
    }



    /**
     * 获取自动关闭申请时间
     * @return array
     */
    private function __getCloseApplyTimeRange()
    {
        return [
            'dayTimeStart'      => Carbon::yesterday()->getTimestamp(),
            'dayTimeEnd'        => Carbon::yesterday()->addHours(23)->addMinutes(59)->addSeconds(59)->getTimestamp(),
        ];
    }

    /**
     * 获取自动完成兼职时间
     * @return array
     */
    private function __getFinishJobTimeRange()
    {
        return [
            'dayTimeStart'      => Carbon::today()->addDays(-7)->getTimestamp(),
            'dayTimeEnd'        => Carbon::today()->addDays(-7)->addHours(23)
                ->addMinutes(59)->addSeconds(59)->getTimestamp()
        ];
    }


}
